package logic;

import java.util.ArrayList;
import java.util.Properties;

import javax.mail.*;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import loginmysql.MysqlLogin;

public class MailSender {
	static String subject = "Fira";

	static String messg = "Fira";

	// Sender's email ID and password needs to be mentioned

	static String from = "tinchobeyer2@gmail.com";

	static String pass = "tinchito";

	// Defining the gmail host

	static String host = "smtp.gmail.com";

	static// Creating Properties object
	Properties props = new Properties();

	static String mssgStart = "<html><body>";
	static String mssgHead = "";
	static String localidad = "";
	static String getLoc;
	static String tableHead;
	static String mssgEnd;
	static String mssgItems = "";
	static String mssgEnc;
	static String result;

	public static String sendEmail(String messg) throws AddressException,
			MessagingException, AuthenticationFailedException {

		System.out.println(messg);
		// Creating a result for getting status that messsage is delivered or
		// not!
		props.put("mail.smtp.host", host);

		props.put("mail.transport.protocol", "smtp");

		props.put("mail.smtp.auth", "true");

		props.put("mail.smtp.starttls.enable", "true");

		props.put("mail.user", from);

		props.put("mail.password", pass);

		props.put("mail.port", "465");

		// Authorized the Session object.

		Session mailSession = Session.getInstance(props,
				new javax.mail.Authenticator() {

					@Override
					protected PasswordAuthentication getPasswordAuthentication() {

						return new PasswordAuthentication(from, pass);

					}

				});

		// Create a default MimeMessage object.

		MimeMessage message = new MimeMessage(mailSession);

		// Set From: header field of the header.

		message.setFrom(new InternetAddress(from));

		MysqlLogin.connect();

		// Set To: header field of the header.
		ArrayList<String> mails = MysqlLogin.getMails();
		for (String mail : mails) {
			message.addRecipient(Message.RecipientType.TO, new InternetAddress(
					mail));
		}

		MysqlLogin.disconnect();
		// Set Subject: header field

		message.setSubject("Fira");

		// Now set the actual message

		message.setContent(messg, "text/html");

		// Send message

		Transport.send(message);

		result = "Operaci&oacute;n exitosa.";

		System.out.println("el resultado " + result);
		return result;

	}
}
